package com.gpoint.rdp.door.user.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.gpoint.rdp.base.core.util.string.StringUtil;
import com.gpoint.rdp.base.db.model.DefaultQueryFilter;
import com.gpoint.rdp.base.core.entity.ResultMessage;
import com.gpoint.rdp.base.framework.page.PageList;
import com.gpoint.rdp.base.framework.page.PageResult;
import com.gpoint.rdp.api.base.query.QueryFilter;
import com.gpoint.rdp.base.web.controller.GenericController;
import com.gpoint.rdp.base.web.json.PageJson;
import com.gpoint.rdp.base.web.util.RequestUtil;
import com.gpoint.rdp.card.department.persistence.dao.DepartmentQueryDao;
import com.gpoint.rdp.card.department.persistence.entity.DepartmentPo;
import com.gpoint.rdp.card.department.service.DepartmentQueryService;
import com.gpoint.rdp.common.DoorConfig;
import com.gpoint.rdp.door.user.service.CampusCardService;
import com.gpoint.rdp.door.user.service.CampusCardQueryService;
import com.gpoint.rdp.door.CurrentPermission.persistence.entity.CurrentPermissionPo;
import com.gpoint.rdp.door.door.persistence.entity.DoorPo;
import com.gpoint.rdp.door.doorPermission.persistence.dao.PermissTypeAndUserDao;
import com.gpoint.rdp.door.doorPermission.persistence.dao.PermissTypeAndUserQueryDao;
import com.gpoint.rdp.door.doorPermission.persistence.entity.PermissTypeAndUserPo;
import com.gpoint.rdp.door.user.persistence.dao.CampusCardQueryDao;
import com.gpoint.rdp.door.user.persistence.entity.CampusCardPo;
import com.gpoint.rdp.base.core.util.AppUtil;
import com.gpoint.rdp.base.core.util.BeanUtils;
import com.gpoint.rdp.base.core.util.JacksonUtil;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/rdp/user/campusCard/")
public class CampusCardController extends GenericController {
	private static final int FORMATCOLUMN = 10;
	@Resource
	private CampusCardService campusCardService;
	@Resource
	private CampusCardQueryService campusCardQueryService;

	
	@Resource
	private DepartmentQueryService departmentQueryService;


	private DoorConfig config = AppUtil.getBean(DoorConfig.class);
	String servicecode = config.getServicecode();

//	@Resource
//	private PermissTypeAndUserQueryDao permissTypeAndUserQueryDao;

	@RequestMapping("getData")
	public @ResponseBody List<CampusCardPo> getTreeData(HttpServletRequest request, HttpServletResponse reponse)
			throws Exception {
		try {
			String listData = campusCardQueryService.findAll();

			List<CampusCardPo> doorZoneList = CampusCardPo.fromJsonArrayString(listData);

			if (BeanUtils.isEmpty(doorZoneList)) {
				doorZoneList = new ArrayList<CampusCardPo>();
			}

			return doorZoneList;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		}
	}

	@RequestMapping("querysno")
	public @ResponseBody PageJson querysno(HttpServletRequest request, HttpServletResponse reponse) throws Exception {
		try {

			// 获取前台数值
			QueryFilter queryFilter = new DefaultQueryFilter();

			String sno = RequestUtil.getString(request, "sno");

			String deptno = RequestUtil.getString(request, "deptno");

			String name = RequestUtil.getString(request, "name");

			queryFilter.addParamsFilter("sno", sno);
			queryFilter.addParamsFilter("ORGCODE", deptno);
			queryFilter.addParamsFilter("name", name);

			// 调用接口查询

			// 调用service 接口方法
			String listData = this.campusCardQueryService.queryPage(queryFilter);

			PageList<CampusCardPo> campusCardList = null;
			// 返回结果集合
			if (JacksonUtil.isJsonObject(listData)) {
				List<CampusCardPo> list = CampusCardPo.fromJsonArrayString(JacksonUtil.getString(listData, "data"));
				PageResult pageResult = PageResult.fromJson(JacksonUtil.getString(listData, "pageResult"));
				campusCardList = new PageList<CampusCardPo>(list, pageResult);

				formatField(queryFilter, campusCardList);
			}

			return new PageJson(campusCardList);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		}
	}

	
	@RequestMapping("listJson")
	public @ResponseBody PageJson listJson(HttpServletRequest request, HttpServletResponse reponse) throws Exception {
		QueryFilter queryFilter = getQuerFilter(request);

		// 如果id不为空查出部分，为空查出全部
//		String id = request.getParameter("id");
//		List<PermissTypeAndUserPo> list2 = null;
//		if (id != null) {
//			// 从用户权限关联表存储表查询分配列表，设置为List，分配设置为true，
//			// 根据不同类型查出 查询出已经分配的userList
//
//			list2 = permissTypeAndUserQueryDao.findByKey("listByType", id);
//		}

		// String typeid = RequestUtil.getString(request, "typeid");

		try {
			String listData = campusCardQueryService.query(queryFilter);
			PageList<CampusCardPo> campusCardList = null;
			if (JacksonUtil.isJsonObject(listData)) {
				List<CampusCardPo> list = CampusCardPo.fromJsonArrayString(JacksonUtil.getString(listData, "data"));
				PageResult pageResult = PageResult.fromJson(JacksonUtil.getString(listData, "pageResult"));

				campusCardList = new PageList<CampusCardPo>(list, pageResult);

				// 检测是否可以集合匹配
//				if (list2 != null && list2.size() > 0) {
//
//					for (int i = 0; i < campusCardList.size(); i++) {
//						CampusCardPo po = campusCardList.get(i);
//
//						for (int j = 0; j < list2.size(); j++) {
//							if (po.getCarduid().equals(list2.get(j).getUseruid())) {
//								po.setSelectedflag(true);
//							}
//						}
////						  if(po.getCarduid().equals("2671322345")) {
////							  po.setSelectedflag(true);
////						  }
//
//					}
//				}

			//	formatField(queryFilter, campusCardList);
			}

			return new PageJson(campusCardList);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new PageJson();
		}
	}

	private void formatField(QueryFilter queryFilter, PageList<CampusCardPo> campusCardList) {
		for (int i = 0; i < campusCardList.size(); i++) {
			CampusCardPo po = campusCardList.get(i);
			String s1 = po.getCarduid();
			String s2 = po.getUsername(); // 姓名

			String s3 = po.getUsernum();// 学工号
			String s4 = po.getOrgcode(); // 根据orgcode查询出部门名称
			// 调用接口查询名称
			String orgname = null;
			String s44 = orgname;
			// 判断orgcode是否为空
			if (s4 == null) {
				s44 = "";
			} else {
				queryFilter.addParamsFilter("ORGCODE", s4);
				queryFilter.addParamsFilter("servicecode", servicecode);
				//String listData1 = departmentQueryDao.queryByQueryFilter("querypage", queryFilter).toString();
				String listData1    = this.campusCardQueryService.queryPage(queryFilter);
				
				// 返回部门查询结果
				if (JacksonUtil.isJsonObject(listData1)) {
					List<DepartmentPo> departlist = DepartmentPo
							.fromJsonArrayString(JacksonUtil.getString(listData1, "data"));
					if (departlist.size() == 0) {
						if (s44 == null) {
							s44 = "";
						}
					} else {
						for (DepartmentPo po1 : departlist) {
							s44 = po1.getOrgname();

						}
					}

				}
			}

			// 分割部门名称
			StringBuilder sb3 = new StringBuilder();
			StringBuilder sb1 = new StringBuilder();
			StringBuilder sb2 = new StringBuilder();
			StringBuilder sb = new StringBuilder();

			if (StringUtil.isEmpty(s3)) {// 学工号
				s3 = "";
			}
			// s3

			if (s3.length() == 10) {
				sb1.append(s3);
			} else if (s3.length() < 10) {
				int length = s3.length();
				sb1.append(s3);
				for (int t = 0; t < FORMATCOLUMN - length; t++) {
					sb1.append("&nbsp;&nbsp;");
				}
			}

			// s2 姓名
			if (StringTest.toGb2312(s2).length == FORMATCOLUMN) {
				sb2.append(s2);
			} else if (StringTest.toGb2312(s2).length < 10) {
				int length = StringTest.toGb2312(s2).length;
				sb2.append(s2);

				// 拼成20个固定字符

				// 英文
				if ("英文".equals(StringTest.checkString(s2))) {

					for (int t = 0; t < FORMATCOLUMN - length; t++) {
						sb2.append("&ensp;");
					}

					// 偶数加上半个
				} else { // 中文

					for (int t = 0; t < FORMATCOLUMN - length; t++) {

						sb2.append("&ensp;");
					}
				}

			} else {
				// 超过长度加...
				String str = s2.substring(0, 5) + "..";
				sb2.append(str);

			}

//					
			// s3 部门
			if (s44.length() == 10) {
				sb3.append(s44);
			} else {
				int length = s44.length();
				sb3.append(s44);
				for (int t = 0; t < FORMATCOLUMN - length; t++) {
					sb3.append("&nbsp;");
				}
			}

			sb.append(sb1);
			sb.append("&nbsp;");
			sb.append(sb2);
			sb.append("&nbsp;");
			sb.append(sb3);

			po.setKey(sb.toString());
			po.setValue(s1 + "," + s3);
		}
	}

	
	@RequestMapping("edit")
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String preUrl = RequestUtil.getPrePage(request);
		String id = RequestUtil.getString(request, "id");
		CampusCardPo campusCard = null;
		if (StringUtil.isNotEmpty(id)) {
			String data = null;
			data = campusCardQueryService.loadCascade(id);
			campusCard = CampusCardPo.fromJsonString(data);
		}

		return getAutoView().addObject("campusCard", campusCard).addObject("returnUrl", preUrl);
	}

	
	@RequestMapping("flowEdit")
	public ModelAndView flowEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String preUrl = RequestUtil.getPrePage(request);
		String id = RequestUtil.getString(request, "id");
		CampusCardPo campusCard = null;
		if (StringUtil.isNotEmpty(id)) {
			String data = null;
			data = campusCardQueryService.loadCascade(id);
			campusCard = CampusCardPo.fromJsonString(data);
		}
		return getAutoView().addObject("campusCard", campusCard).addObject("returnUrl", preUrl);
	}

	
	@RequestMapping("get")
	public ModelAndView get(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String preUrl = RequestUtil.getPrePage(request);
		String id = RequestUtil.getString(request, "id");
		CampusCardPo campusCard = null;
		if (StringUtil.isNotEmpty(id)) {
			String data = null;
			data = campusCardQueryService.loadCascade(id);
			campusCard = CampusCardPo.fromJsonString(data);
		}
		return getAutoView().addObject("campusCard", campusCard).addObject("returnUrl", preUrl);
	}

	
	@RequestMapping("save")
	public void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ResultMessage message = null;
		try {
			String json = RequestUtil.getString(request, "json");
			campusCardService.saveCascade(json);
			message = new ResultMessage(ResultMessage.SUCCESS, "保存校园卡信息表成功");
		} catch (Exception e) {
			message = new ResultMessage(ResultMessage.FAIL, "对校园卡信息表操作失败," + e.getMessage());
			logger.error("对校园卡信息表操作失败，" + e.getMessage(), e);
		}
		writeResultMessage(response.getWriter(), message);
	}

	
	@RequestMapping("remove")
	public void remove(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ResultMessage message = null;
		try {
			// 获得待删除的id
			String[] ids = RequestUtil.getStringAryByStr(request, "id");
			campusCardService.deleteByIdsCascade(ids);
			message = new ResultMessage(ResultMessage.SUCCESS, "删除校园卡信息表成功");
		} catch (Exception e) {
			message = new ResultMessage(ResultMessage.FAIL, "删除校园卡信息表失败，" + e.getMessage());
			logger.error("删除校园卡信息表失败，" + e.getMessage(), e);
		}
		writeResultMessage(response.getWriter(), message);
	}

	@RequestMapping("list")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = getAutoView();
		return mv;

	}

	
	@RequestMapping("permissionUserList")
	public @ResponseBody PageJson permissionUserList(HttpServletRequest request, HttpServletResponse reponse)
			throws Exception {
		QueryFilter queryFilter = getQuerFilter(request);
		try {

			PageList<PermissTypeAndUserPo> permissTypeAndUserList = null;
			List<PermissTypeAndUserPo> list = new ArrayList<PermissTypeAndUserPo>();
			PageResult pageResult = new PageResult();
			permissTypeAndUserList = new PageList<PermissTypeAndUserPo>(list, pageResult);
			return new PageJson(permissTypeAndUserList);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new PageJson();
		}
	}

	
	@RequestMapping("listByIds")
	public @ResponseBody PageJson listByIds(@RequestParam String ids, HttpServletRequest request,
			HttpServletResponse reponse) throws Exception {
		QueryFilter queryFilter = getQuerFilter(request);
		PageList<CampusCardPo> campusCardList = null;
		if (StringUtil.isNotEmpty(ids)) {
			String sqlStr = arrStrToSqlStr(ids);
			queryFilter.addParamsFilter("whereSql", "usernum in " + sqlStr);
		} else {
			List<CampusCardPo> list = new ArrayList<CampusCardPo>();
			PageResult pageResult = new PageResult();
			campusCardList = new PageList<CampusCardPo>(list, pageResult);
			return new PageJson(campusCardList);
		}
		try {
			String listData = campusCardQueryService.query(queryFilter);
			if (JacksonUtil.isJsonObject(listData)) {
				List<CampusCardPo> list = CampusCardPo.fromJsonArrayString(JacksonUtil.getString(listData, "data"));
				PageResult pageResult = PageResult.fromJson(JacksonUtil.getString(listData, "pageResult"));
				campusCardList = new PageList<CampusCardPo>(list, pageResult);
			}

			return new PageJson(campusCardList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new PageJson();
		}
	}

	@RequestMapping("listByOrgcode")
	public @ResponseBody PageJson listByOrgcode(@RequestParam String orgcode, HttpServletRequest request,
			HttpServletResponse reponse) throws Exception {
		QueryFilter queryFilter = getQuerFilter(request);
		queryFilter.addParamsFilter("servicecode", servicecode);
		if (StringUtil.isNotEmpty(orgcode)) {
			String sqlStr = arrStrToSqlStr(orgcode);
			queryFilter.addParamsFilter("orgcode", sqlStr);
		}
		try {
			String listData = campusCardQueryService.query(queryFilter);
			PageList<CampusCardPo> campusCardList = null;
			if (JacksonUtil.isJsonObject(listData)) {
				List<CampusCardPo> list = CampusCardPo.fromJsonArrayString(JacksonUtil.getString(listData, "data"));
				PageResult pageResult = PageResult.fromJson(JacksonUtil.getString(listData, "pageResult"));
				campusCardList = new PageList<CampusCardPo>(list, pageResult);
			}

			return new PageJson(campusCardList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new PageJson();
		}
	}

	private String arrStrToSqlStr(String arrStr) {
		String sqlStr = "";
		StringBuffer sb = new StringBuffer("(");
		String[] strArr = arrStr.split(",");
		for (int i = 0; i < strArr.length; i++) {
			sb.append("'").append(strArr[i]).append("'");
			if (i != strArr.length - 1) {
				sb.append(",");
			} else {
				sb.append(")");
			}
		}
		sqlStr = sb.toString();
		return sqlStr;
	}

}